package Controller.User;


import Dto.User;
import MyException.MyException;
import Service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "register", value = "/Register")
public class Register extends HttpServlet {
    UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String nickname = request.getParameter("nickname");
        String inputCode = request.getParameter("code");
        String password = request.getParameter("password");
        HttpSession session = request.getSession();
        response.setContentType("text/html;charset=utf-8");
        String code = (String) session.getAttribute("captchaCode");
        try{
            if (!code.equals(inputCode)){
                request.setAttribute("msg","验证码错误或为空");
                request.getRequestDispatcher("/register.jsp").forward(request,response);
                return;
            }
            //检查用户名是否重复
            User user = userService.register(username);
            User loginUser = new User();
            loginUser.setUsername(username);
            loginUser.setPassword(password);
            loginUser.setNickname(nickname);
            //user为空代表着数据库内没有重复改用户,可以注册
            if (user == null){
                userService.addRegister(loginUser);
                request.setAttribute("user",loginUser);
                session.setAttribute("nickname",nickname);
                request.setAttribute("msg","注册成功，请登录");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }
        }catch (MyException e){
            request.setAttribute("msg",e.getMessage());
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }catch (SQLException e){
            e.printStackTrace();
            System.out.println("sql异常");
        }
    }
}
